package com.xpec.c4.h5net;

import java.nio.ByteBuffer;

public class BytebufferByte {

	public static byte[] bytebuffer2Byte(ByteBuffer buffer) {
		buffer.clear();
		byte[] byteArray = new byte[buffer.remaining()];
		buffer.get(byteArray);
		return byteArray;
	}

	public static ByteBuffer byte2Bytebuffer(byte[] byteArray) {
		return ByteBuffer.wrap(byteArray);
	}

	public static byte[] bytebuffer2ByteByRange(ByteBuffer buffer, int index,
			int length) {
		buffer.clear();
		byte[] byteArray = new byte[length];
		buffer.get(byteArray, index, length);
		return byteArray;
	}

	public static byte[] bytebuffer2ByteByRangeAndRemove(ByteBuffer buffer,
			int index, int length) {
		buffer.clear();
		byte[] byteArray = new byte[length];
		buffer.get(byteArray, index, length);
		removeBytesFromByteBuffer(buffer, index, length);
		return byteArray;
	}

	public static ByteBuffer mergeByteArraysToBuffer(int totalSize, byte[]... byteArrays) {
		ByteBuffer totalBuffer = ByteBuffer.allocate(totalSize);
		for (byte[] byteArray : byteArrays) {
			totalBuffer.put(byteArray);
		}
		totalBuffer.clear();
		return totalBuffer;
	}

	public static byte[] mergeByteArrays(int totalSize, byte[]... byteArrays) {
		ByteBuffer totalBuffer = ByteBuffer.allocate(totalSize);
		for (byte[] byteArray : byteArrays) {
			totalBuffer.put(byteArray);
		}
		totalBuffer.clear();
		return bytebuffer2Byte(totalBuffer);
	}

	public static void removeBytesFromByteBuffer(ByteBuffer buffer, int index,
			int length) {
		buffer.clear();
		buffer.put((new byte[length]), index, length);
		for (int i = index ; i < (buffer.limit() - length) ; i++) {
			buffer.put(i, buffer.get(i + length));
			buffer.put((i + length), (byte) 0);
		}
	}

}
